class ProjectsController < ApplicationController
  before_filter :get_project, :authorized?, :project_will_be_deleted?, :except => [:index, :new, :create]
  
  def get_project
    begin
      @project = current_user.projects.find(params[:id])
    rescue
      flash[:notice] = I18n.t :dont_have_permission, :scope => :permission
      redirect_to root_path
    end
  end
  
  def index
    @projects = current_user.projects
    
    @logs = Log.all(:conditions => {:project_id => @projects}, 
                    :order => "created_at DESC",
                    :limit => 20)
                    
    @late_milestones = Milestone.late.all(:conditions => {:project_id => @projects})
    
    @my_activities = current_user.activities.open.all(:order => "project_id")
    
    if @projects.size > 0
      render :layout => "two_columns_tiny_left"
    else
      render :layout => "one_column"
    end
  end

  def show
    @late_milestones = @project.milestones.late.all(:include => :activities)
    @my_activities = current_user.activities.open.all(:conditions => {:project_id => @project.id})
    
    @logs = @project.logs.all(:limit => 20)
  end

  def new
    @project = current_user.projects.new
    
    render :layout => "one_column"
  end

  def edit
  end

  def create 
    @project = current_user.build_project(params[:project])
    
    begin 
      @project.save!
      redirect_to @project
    rescue
      render :action => "new"
    end
  end
  
  def update
    if @project.update_attributes(params[:project])
      flash[:success] = I18n.t :updated, :scope => [:project, :messages, :success]
      redirect_to project_path(@project)
    else
      render :action => "edit"
    end
  end
end
